// 本文件处理数据逻辑

import React, {createContext, useReducer, useEffect} from 'react';
import {fetchCsvData} from "./api";
import initialState from './data';
import reducer from './reducer';

// 创建数据中心的这样一个上下文，一般称为store
const store = createContext();

// 包装成数据组件
function StateProvider({children}) {
    // 绑定数据以及数据处理方法
    const [state, dispatch] = useReducer(reducer, initialState);

    // 初始化时，读取本地数据
    useEffect(() => {
        let data=new Array();let t;
        fetchCsvData('./data/2015.csv').then(res=>{
            t=res;data.push(t);
            fetchCsvData('./data/2016.csv').then(res=>{
                t=res;data.push(t);
                fetchCsvData('./data/2017.csv').then(res=>{
                    t=res;data.push(t);
                    fetchCsvData('./data/2018.csv').then(res=>{
                        t=res;data.push(t);
                        fetchCsvData('./data/2019.csv').then(res=>{
                            t=res;data.push(t);
                            fetchCsvData('./data/2020.csv').then(res=>{
                                t=res;data.push(t);
                                fetchCsvData('./data/2021.csv').then(res=>{
                                t=res;data.push(t);
                                    dispatch({
                                        type: 'init',
                                        payload: data
                                    })
                                })
                            })
                        })
                    })
                })
            })
        })
        // data.push(fetchCsvData('./data/2016.csv'));
        // fetchCsvData('./data/2015.csv').then(res=>{data.push(res)})
        // fetchCsvData('./data/2016.csv').then(res=>{data.push(res)})
        // .then(() => {
        // })
    }, [])

    // 为子元素包裹上数据的上下文环境，方便所有子元素读取
    return <store.Provider value={{state, dispatch}}>
        {children}
    </store.Provider>
}

// console.log(store);

export {store, StateProvider}
